/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef IMAGE_KNIFE_C_KEKE_TASK_WORKER_FFRT_H
#define IMAGE_KNIFE_C_KEKE_TASK_WORKER_FFRT_H

#include "task_worker.h"
#include "ffrt/queue.h"

namespace ImageKnifePro {

class TaskWorkerFFRT : public TaskWorker {
public:
    class TaskHandleFFRT : public TaskHandle {
    public:
        std::function<void()> onCancelSuccess = nullptr;
        explicit TaskHandleFFRT(ffrt_task_handle_t handle) : handle_(handle)
        {
        }
        void CancelTask() override;
        ~TaskHandleFFRT() override;
    private:
        bool canceled_ = false;
        ffrt_task_handle_t handle_ = nullptr;
    };

    TaskWorkerFFRT();

    bool PushTask(AsyncFunc execute, AsyncFunc complete, void *data, std::string taskInfo = "",
                  ImageKnifeQOS qos = ImageKnifeQOS::DEFAULT) override;

    bool PushTask(AsyncTask execute, AsyncTask complete, std::shared_ptr<ImageKnifeTaskInternal> task,
                          ImageKnifeQOS qos = ImageKnifeQOS::DEFAULT) override;

    void ToMainThread(std::function<void(void*)> func, void* data) override;

    std::shared_ptr<TaskHandle> ToMainThreadWithDelay(std::function<void(void*)> func,
                                                      void* data, uint32_t milliSecond) override;

    void SetMaxConcurrency(uint64_t concurrency) override;

    ~TaskWorkerFFRT() override;
private:
    ffrt_queue_t taskQueue_ = nullptr;
    ffrt_queue_t apiQueue_ = nullptr;
    ffrt_queue_t mainQueue_ = nullptr;

    struct FuncData {
        AsyncFunc execute = nullptr;
        AsyncFunc complete = nullptr;

        void *data = nullptr;
    };

    struct TaskData {
        AsyncTask executeTask = nullptr;
        AsyncTask completeTask = nullptr;
        std::shared_ptr<ImageKnifeTaskInternal> task = nullptr;
    };

    void CreateTaskQueue(uint64_t maxConcurrency = 8);
    void CreateApiQueue();

    static void TaskCallback(void* arg);
    static void ExecuteCallback(void* arg);
    static void MainThreadCallback(void* arg);
};

}

#endif //IMAGE_KNIFE_C_KEKE_TASK_WORKER_FFRT_H
